# frozen_string_literal: true

# The task api
namespace '/task' do
  helpers ApiHelpers
  before { inject_params }

  post '/add' do
    task = Task.create!(body: @json_params[:body])
    task.to_json
  end

  post '/login' do
    'true'
  end

  post '/list' do
    # puts @json_params

    tasks = if @json_params[:task_type] == 'draft'
              Task.draft.valid
            else Task.planned.valid
            end

    {
      code: 'ok',
      payload: {
        objs: tasks
      }
    }.to_json
    # Oj.dump(tasks)
  end

  get '/box' do
    Task.valid.draft.to_json
  end

  put '/update' do
    target = Task.find(@json_params[:t_id])
    params = @json_params.except(:_id, :t_id)
    target.update_attributes(params)
    @json_params.to_json
  end

  post '/delete' do
    puts @json_params
    task = Task.find(@json_params[:task_id])
    task.destroy!
    {
      code: 'ok',
      payload: {
        obj_id: @json_params[:task_id]
      }
    }.to_json
  end

  post '/create' do
    puts @json_params
    task = Task.create!(body: @json_params[:task_body], title: @json_params[:task_title])
    {
      code: 'ok',
      payload: {
        obj: task
      }
    }.to_json
  end

  post '/update' do
    puts @json_params
    target = Task.find(@json_params[:t_id])
    target.update_attributes({ title: @json_params[:task_title], body: @json_params[:task_body] })
    {
      code: 'ok',
      payload: {
        obj: target
      }
    }.to_json
  end

  post '/add_tag' do
    puts @json_params
    task = Task.find(@json_params[:t_id])
    task.add_tag!(@json_params[:tag_name])
    {
      code: 'ok',
      payload: {
        obj: task
      }
    }.to_json
  end
end
